import React from 'react'
import './index.scss'
import { useNavigate } from 'react-router-dom'
import { ArrowLeft } from '@react-vant/icons';
import { Form, Input, Button, Space, Toast } from 'antd-mobile'
import { useState, useEffect } from "react";
import api from '../../util/api';

export default function Index() {
    const navigate = useNavigate()
    const [phone, setPhone] = useState('')
    const [password, setPassword] = useState('')
    const [timer, setTimer] = useState(0);
    const [isTimerActive, setIsTimerActive] = useState(false);
    const [yzm, setYzm] = useState('')

    const phoneRule = (e: React.FocusEvent<HTMLInputElement, Element>) => {
        let newValue = e.target.value
        if (newValue.length == 11) {
            api.post('/cwp/isuser', { user: newValue }).then(res => {
                if (res.code !== 200) {
                    Toast.show({
                        content: res.message,
                        maskClickable: false,
                    })
                }
            })
        }
    }
    const handlePhone = (e: React.SetStateAction<string>) => {
        setPhone(e)
    }
    const handlePassword = (e: React.SetStateAction<string>) => {
        setPassword(e)
    }
    const handleCode = (e: React.SetStateAction<string>) => {
        setYzm(e)
    }
    useEffect(() => {
        let intervalId = null

        if (isTimerActive) {
            intervalId = setInterval(() => {
                setTimer(prevTimer => prevTimer - 1);
            }, 1000);
        }
        // 清除验证码
        if (localStorage.getItem('code')) {
            setTimeout(() => {
                localStorage.removeItem('code');
            }, 120000);
        }

        return () => {
            clearInterval(intervalId);
        };
    }, [isTimerActive]);

    const handleSendCode = () => {
        // 发送验证码逻辑
        api.post('/cwp/getcode', { phone }).then(res => {
            if (res.code === 200) {
                localStorage.setItem('code', JSON.stringify({ code: res.yanZhengMa }))
            }
        })
        // 开始倒计时
        setTimer(60);
        setIsTimerActive(true);
    };
    const submit = () => {
        let { code } = JSON.parse(localStorage.getItem('code'));
        if (yzm == code) {
            console.log('验证码正确');

        }
        api.post('/cwp/changepassword', { phone, password }).then(res => {
            if (res.code === 200) {
                Toast.show({
                    content: res.msg,
                    maskClickable: false,
                })
                // 三秒后跳转到登录页面
                setTimeout(() => {
                    navigate('/login')
                }, 3000)
            } else {
                Toast.show({
                    content: res.msg,
                    maskClickable: false,
                })
            }
        })
    }
    return (
        <div className='forget-wrapper'>
            <div className="forget-top">
                <ArrowLeft fontSize="2em" onClick={() => navigate(-1)} />
            </div>
            <div className='forget-text'>
                <span>输入手机号，获取验证码</span>
            </div>
            <div className='form'>
                <Form layout='horizontal' mode='card'>
                    <Form.Item
                        rules={[
                            { required: true, message: "请填写手机号" },
                            { pattern: /^1[3456789]\d{9}$/, message: "请填写正确的手机号" },
                        ]}
                        name="phone"
                        label='手机号'>
                        <Input
                            placeholder='请输入'
                            value={phone}
                            onBlur={(e) => phoneRule(e)}
                            onChange={handlePhone}
                        />
                    </Form.Item>
                    <Form.Item
                        name='code'
                        label="短信验证码"
                        // 6位数字
                        rules={[
                            { required: true, message: "请填写验证码" },
                            {
                                pattern: /^[0-9]{6}$/,
                                message: "请输入6位数字"
                            }
                        ]}
                        extra={
                            <Button disabled={timer > 0} onClick={handleSendCode}>
                                {timer > 0 ? `${timer}秒后重新发送` : "获取验证码"}
                            </Button>
                        }>

                        <Input
                            placeholder="请输入验证码"
                            onChange={handleCode}
                        />
                    </Form.Item>

                    <Form.Item
                        name="password"
                        label="密码"
                        rules={[
                            { required: true, message: "请填写密码" },
                            {
                                pattern: /^[A-Z][a-z0-9]{7,16}$/,
                                message: "大写字母开头，其余部分是数字+小写字母，共8-16位数"
                            }
                        ]}
                    >
                        <Input
                            type="password"
                            placeholder='请输入密码'
                            onChange={handlePassword}
                            value={password}
                        />
                    </Form.Item>
                    <Form.Item
                        name="confirmPassword"
                        label="确认密码"
                        rules={[
                            { required: true, message: "请填写确认密码" },
                            () => ({
                                validator(rule, value) {
                                    if (!value || password === value) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject('两次输入的密码不一致');
                                },
                            }),
                        ]}
                    >
                        <Input type="password" placeholder='请确认密码' />
                    </Form.Item>
                    <Form.Item>
                        <Space>
                            <Button color='success' onClick={submit}>确认</Button>
                        </Space>
                    </Form.Item>
                </Form>
            </div>
        </div>
    )
}
